package xq.gwt.ui.crud;

import xq.gwt.mvc.model.BooleanPropertyModel;
import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.model.PersistableEntityModel;
import xq.gwt.ui.crud.localization.CrudDictionary;

public class NewEntityCommand implements CommandModel{		
	private static final long serialVersionUID = -4082842118663912338L;
	private BooleanPropertyModel enabled = new BooleanPropertyModel();
	private PersistableEntityModel prototype;	
	private EntityEditorModel editorModel;
	private String feedBack;

	public NewEntityCommand(PersistableEntityModel prototype, EntityEditorModel editorModel){
		this.prototype = prototype;
		enabled = new BooleanPropertyModel();
		updateEnabled();
		this.editorModel = editorModel;
	}
	
	public NewEntityCommand(EntityEditorModel editorModel){		
		enabled = new BooleanPropertyModel();
		updateEnabled();
		this.editorModel = editorModel;
	}
	
	
	
	private void updateEnabled(){
		if (prototype == null){
			enabled.setValue(false);
		} else {
			enabled.setValue(true);
		}
			
	}
	
	public void setPrototype(PersistableEntityModel prototype){
		this.prototype = prototype;
		updateEnabled();
	}
	
	@Override
	public void execute() throws Exception {		
		feedBack = null;	
		if(prototype == null)
			return;
		editorModel.setEntity(prototype.newInstance());		
	}

	@Override
	public String getCaption() {			
		return CrudDictionary.Constants().new_caption();
	}

	@Override
	public String getName() {			
		return "New";
	}

	@Override
	public BooleanPropertyModel isEnabled() {
		return enabled;
	}

	@Override
	public String getFeedback() {		
		return feedBack;
	}
	
}
